Client side component API
Posted on 2023-07-08 by
henrikvilhelmberglundUntil now we have been using Svelte components in other Svelte components where we import them and then write the tag for the component <Component></Component>
.
What if we want to use them somewhere else? This is where the client side component API comes in.
This is the normal way we use components in Svelte.
X
=
1
<script>
import Component from "./Component.svelte";
</script>
<Component on:product={(e) => console.log("product", e.detail)} />
<style>
</style>
Using the client side component API we can use the exported class directly.
Here is my vanilla HTML and JS page
I'm not sure how to effectively display this but pretend this is vanilla HTML and .js.
<script>
import { browser } from "$app/environment";
import Component from "./Component.svelte";
let component;
if (browser) {
component = new Component({
target: document.querySelector("#my-vanilla-HTML-and-JS-page"),
props: {
a: 5,
b: 10,
},
context: new Map([["c", 20]]),
// anchor: document.querySelector("#footer")
intro: true,
});
// slightly stupid but I have two instances of the component
document.querySelectorAll("#random")[1].addEventListener("click", () => {
component.$set({
a: Math.floor(Math.random() * 100),
b: Math.floor(Math.random() * 100),
});
});
document.querySelectorAll("#reset")[1].addEventListener("click", () => {
component.reset();
});
document.querySelectorAll("#destroy")[1].addEventListener("click", () => {
component.$destroy();
});
component.$on("product", (e) => {
console.log("product event", e.detail);
});
}
</script>
<style>
</style>